#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <errno.h>

#include <qtts.h>
#include <msp_cmn.h>
#include <msp_errors.h>
#pragma warning(disable:4996)
#pragma comment(lib,"msc_x64.lib") // x64

/* WAV audio header format */
typedef struct _wave_pcm_hdr
{
    char            riff[4];                // = "RIFF"
    int             size_8;                 // = FileSize - 8
    char            wave[4];                // = "WAVE"
    char            fmt[4];                 // = "fmt "
    int             fmt_size;               // = Size of the fmt chunk : 16

    short int       format_tag;             // = PCM : 1
    short int       channels;               // = Number of channels : 1
    int             samples_per_sec;        // = Sample rate : 8000 | 6000 | 11025 | 16000
    int             avg_bytes_per_sec;      // = Average bytes per second : samples_per_sec * bits_per_sample / 8
    short int       block_align;            // = Block align : wBitsPerSample / 8
    short int       bits_per_sample;        // = Bits per sample: 8 | 16

    char            data[4];                // = "data";
    int             data_size;              // = Data size : FileSize - 44 
} wave_pcm_hdr;

/* Default WAV header */
wave_pcm_hdr default_wav_hdr =
{
    { 'R', 'I', 'F', 'F' },
    0,
    {'W', 'A', 'V', 'E'},
    {'f', 'm', 't', ' '},
    16,
    1,
    1,
    16000,
    32000,
    2,
    16,
    {'d', 'a', 't', 'a'},
    0
};

/* Text to Speech */
int text_to_speech(const char* src_text, const char* des_path, const char* params)
{
    int          ret = -1;
    FILE* fp = NULL;
    const char* sessionID = NULL;
    unsigned int audio_len = 0;
    wave_pcm_hdr wav_hdr = default_wav_hdr;
    int          synth_status = MSP_TTS_FLAG_STILL_HAVE_DATA;

    if (NULL == src_text || NULL == des_path)
    {
        printf("params is error!\n");
        return ret;
    }
    fp = fopen(des_path, "wb");
    if (NULL == fp)
    {
        printf("open %s error.\n", des_path);
        return ret;
    }
    /* Start synthesis */
    sessionID = QTTSSessionBegin(params, &ret);
    if (MSP_SUCCESS != ret)
    {
        printf("QTTSSessionBegin failed, error code: %d.\n", ret);
        fclose(fp);
        return ret;
    }
    ret = QTTSTextPut(sessionID, src_text, (unsigned int)strlen(src_text), NULL);
    if (MSP_SUCCESS != ret)
    {
        printf("QTTSTextPut failed, error code: %d.\n", ret);
        QTTSSessionEnd(sessionID, "TextPutError");
        fclose(fp);
        return ret;
    }
    fwrite(&wav_hdr, sizeof(wav_hdr), 1, fp); // Write WAV header with sample rate 16000
    while (1)
    {
        /* Get synthesized audio */
        const void* data = QTTSAudioGet(sessionID, &audio_len, &synth_status, &ret);
        if (MSP_SUCCESS != ret)
            break;
        if (NULL != data)
        {
            fwrite(data, audio_len, 1, fp);
            wav_hdr.data_size += audio_len; // Update data_size
        }
        if (MSP_TTS_FLAG_DATA_END == synth_status)
            break;
    }
    printf("\n");
    if (MSP_SUCCESS != ret)
    {
        printf("QTTSAudioGet failed, error code: %d.\n", ret);
        QTTSSessionEnd(sessionID, "AudioGetError");
        fclose(fp);
        return ret;
    }
    /* Update WAV header with actual data size */
    wav_hdr.size_8 += wav_hdr.data_size + (sizeof(wav_hdr) - 8);

    /* Rewrite the header with updated values, audio file is in WAV format */
    fseek(fp, 4, 0);
    fwrite(&wav_hdr.size_8, sizeof(wav_hdr.size_8), 1, fp); // Write size_8 value
    fseek(fp, 40, 0); // Move file pointer to the location of data_size
    fwrite(&wav_hdr.data_size, sizeof(wav_hdr.data_size), 1, fp); // Write data_size value
    fclose(fp);
    fp = NULL;
    /* End synthesis session */
    ret = QTTSSessionEnd(sessionID, "Normal");
    if (MSP_SUCCESS != ret)
    {
        printf("QTTSSessionEnd failed, error code: %d.\n", ret);
    }

    return ret;
}

int aisound(const char* filename, const char* text)
{
    int         ret = MSP_SUCCESS;
    const char* login_params = "appid = 02fca5ca, work_dir = ."; 
    const char* session_begin_params = "engine_type = local, voice_name = xiaoyan, text_encoding = UTF8, tts_res_path = fo|res\\tts\\xiaoyan.jet;fo|res\\tts\\common.jet, sample_rate = 16000, speed = 100, volume = 50, pitch = 50, rdn = 2";
    /* User login */
    ret = MSPLogin(NULL, NULL, login_params); // First parameter is user name, second is password, third is login parameters. If NULL, it uses default values.
    if (MSP_SUCCESS != ret)
    {
        printf("MSPLogin failed, error code: %d.\n", ret);
        goto exit; // Login failed, exit the program
    }


    /* Text to Speech */
    ret = text_to_speech(text, filename, session_begin_params);
    if (MSP_SUCCESS != ret)
    {
        printf("text_to_speech failed, error code: %d.\n", ret);
    }
   

exit:
    // Logout
    MSPLogout(); 
    return 0;
}